package com.lottery.service;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;

import com.lottery.model.Ticket;

@Component
public class TicketService extends BaseService<Ticket> {

	@Override
	public void setClassM() {
		classM = Ticket.class;		
	}

	public Ticket getWinTicket(String prizeId) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Ticket.class);
		criteria.add(Restrictions.isNull("prize"));
		criteria.setProjection(Projections.rowCount());
		long total = (Long)getHibernateTemplate().findByCriteria(criteria).iterator().next();
		
		long index = -1;
		while(index >= total || index < 0) {
			index = Math.round(Math.random() * total);
		}
		
		criteria.setProjection(null);
		Ticket ticket = (Ticket)getHibernateTemplate().findByCriteria(criteria, (int)index, 1).get(0);
		ticket.setPrize(prizeId);
		getHibernateTemplate().update(ticket);
		
		return ticket;
	}
	
	public List<Ticket> getAllWinTicket() {
		DetachedCriteria criteria = DetachedCriteria.forClass(Ticket.class);
		criteria.add(Restrictions.isNotNull("prize"));
		
		return (List<Ticket>)getHibernateTemplate().findByCriteria(criteria);
	}
	
	public boolean isExist(String code) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Ticket.class);
		criteria.add(Restrictions.eq("code", code));
		List list = getHibernateTemplate().findByCriteria(criteria);
		
		if(list != null && list.size() > 0) {
			return true;
		}
		else {
			return false;
		}
	}
	
	public Ticket getAwardTicketByCode(String code) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Ticket.class);
		criteria.add(Restrictions.eq("code", code));
		criteria.add(Restrictions.isNotNull("prize"));
		List list = getHibernateTemplate().findByCriteria(criteria);
		
		if(list != null && list.size() > 0) {
			return (Ticket)list.get(0);
		}
		else {
			return null;
		}
	}
	
	/*
	public boolean setTicketToAward(String code) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Ticket.class);
		criteria.add(Restrictions.eq("code", code));
		criteria.add(Restrictions.isNotNull("prize"));
		List list = getHibernateTemplate().findByCriteria(criteria);
		
		if(list != null && list.size() > 0) {
			Ticket ticket = (Ticket)list.get(0);
			ticket.setAward(true);
			
			saveOrUpdate(ticket);
			
			return true;
		}
		else {
			return false;
		}
	}
	*/
}
